package com.wbao.dianniu.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.powerfulrecyclerview.listener.OnRefreshListener;
import com.powerfulrecyclerview.ptr.HistoryThemeHeaderView;
import com.powerfulrecyclerview.ptr.PowerfulRecyclerView;
import com.powerfulrecyclerview.ptr.SimDividerItemDecoration;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.QAInfoAdapter;
import com.wbao.dianniu.customView.ClearEditText;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleActionListener;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.im.AddFriendActivity;
import com.wbao.dianniu.listener.IQaListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.update.QaDataChangeManager;
import com.wbao.dianniu.update.QaDataChangeManager.IQaDataListener;
import com.wbao.dianniu.manager.QaManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 问答搜索
 *
 * @author yejianjun
 */
public class QaSearchActivity extends Activity implements IQaListener, IQaDataListener, View.OnClickListener, OnRefreshListener, QAInfoAdapter.OnItemClickListener {

    private ClearEditText clearEditText;
    private QaManager manager;
    private QAInfoAdapter adapter;
    private final int PAGE_COUNTS = 10;
    //    private PullToRefreshListView mListView;
//    private ListView actualListView;
    private PowerfulRecyclerView recyclerView;
    private String searchContent;
    private LinearLayout noDataLayout;
    private ImageView backIV;
    private Button cancelBtn;
    private TextView addFriend, jobTV, recruitTV, actTV, nearTV;
    private TextView noDataTV;
    private QaDataChangeManager qaDataChangeManager;
    private RecyclerView.LayoutManager mLayoutManager;
    private HistoryThemeHeaderView header;
    // 是否上拉加载更多
    private int lastVisibleItem = 0;
    private Dialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_qa_search);
        initManager();
        initView();
        initBaseView();
        initLoadMoreListener();
    }

    private void initManager() {
        manager = new QaManager(this);
        manager.addQaListener(this);
        qaDataChangeManager = QaDataChangeManager.getInstance();
        qaDataChangeManager.addQaChangeListener(this);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    }

    /**
     * 上拉加载更多
     */
    private void initLoadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    //设置正在加载更多
                    adapter.changeMoreStatus(QAInfoAdapter.LOADING_MORE);
                    // 上拉刷新 加载请求数据
                    pullUpRequest();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void initView() {
        cancelBtn = findViewById(R.id.title_search_cancel);
        cancelBtn.setOnClickListener(this);
        backIV = findViewById(R.id.title_search_back);
        backIV.setOnClickListener(this);
        // 先屏蔽返回按钮
        backIV.setVisibility(View.GONE);
        clearEditText = findViewById(R.id.title_search_clearET);
        clearEditText.setHint(getResources().getString(R.string.qa_search_hint));
        noDataLayout = findViewById(R.id.search_nodata_layout);
        noDataLayout.setVisibility(View.VISIBLE);
        noDataTV = findViewById(R.id.no_data_tv);

        adapter = new QAInfoAdapter(this);
        adapter.setOnItemClickListener(this);
        adapter.changeMoreStatus(QAInfoAdapter.PULLUP_LOAD_MORE);

        recyclerView = findViewById(R.id.search_qa_listview);
        recyclerView.setAdapter(adapter);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        // 设置分割线
        recyclerView.addItemDecoration(new SimDividerItemDecoration(this));
        // 设置adapter
        header = (HistoryThemeHeaderView) LayoutInflater.from(this).inflate(R.layout.history_header_theme, recyclerView, false);
        recyclerView.setHeaderView(header);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshEnable(false);
        recyclerView.setOnRefreshListener(this);

        /*mListView = (PullToRefreshListView) findViewById(R.id.search_qa_listview);
        mListView.setMode(Mode.PULL_UP_TO_REFRESH);
        mListView.setOnRefreshListener(onRefreshListener);

        actualListView = mListView.getRefreshableView();
        registerForContextMenu(actualListView);
        actualListView.setAdapter(adapter);
        actualListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                ActivityUtils.intoQaDetailActivity(QaSearchActivity.this, (QaResponse) adapter.getItem(position - 1));
            }
        });*/
        /*clearEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    adapter.cleanData();
                    searchContent = clearEditText.getText().toString().trim();
                    requstData(searchContent, "down");
                    return true;
                }
                return false;
            }
        });*/
        clearEditText.setOnEditorActionListener(new NoDoubleActionListener() {
            @Override
            public void noDoubleAciton() {
                showDialog();
                adapter.cleanData();
                searchContent = clearEditText.getText().toString().trim();
                requstData(searchContent, "down");
            }
        });

    }

    private void showDialog() {
        /*if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }*/
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
    }

    private void initBaseView() {
        addFriend = findViewById(R.id.other_include_friend);
        jobTV = findViewById(R.id.other_include_job);
        recruitTV = findViewById(R.id.other_include_recruit);
        actTV = findViewById(R.id.other_include_act);
        nearTV = findViewById(R.id.other_include_near);
        addFriend.setOnClickListener(this);
        jobTV.setOnClickListener(this);
        recruitTV.setOnClickListener(this);
        actTV.setOnClickListener(this);
        nearTV.setOnClickListener(this);
    }

    /*OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            //  上拉刷新 加载请求数据
            pullUpRequest();
        }
    };*/

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        requstData(searchContent, "up");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeQaListener(this);
        }
        if (null != qaDataChangeManager) {
            qaDataChangeManager.removeQaChangeListener(this);
        }
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
           /* case R.id.search_imagebutton01:
                Utils.hideSoftInput(QaSearchActivity.this, clearEditText);
                String content = clearEditText.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                adapter.cleanData();
                searchContent = clearEditText.getText().toString().trim();
                currentPage = 1;
                requstData(searchContent, currentPage);
                break;*/
            case R.id.other_include_friend:
                intent(AddFriendActivity.class);
                break;
            case R.id.other_include_job:
                intent(ComRecruitActivity.class);
                break;
            case R.id.other_include_recruit:
                intent(JobListActivity.class);
                break;
            case R.id.other_include_act:
                Intent offline_intent = new Intent();
                offline_intent.putExtra(Const.BUNDLE_DATA, "");
                offline_intent.setClass(this, OfflineActivity.class);
                startActivity(offline_intent);
                break;
            case R.id.other_include_near:
                intent(KnowListActivity.class);
                break;
            case R.id.title_search_back:
            case R.id.title_search_cancel:
                this.finish();
                break;
            default:
                break;
        }

    }

    private void intent(Class cls) {
        Intent intent = new Intent();
        intent.setClass(QaSearchActivity.this, cls);
        startActivity(intent);
    }

    /*OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            QaResponse resp = (QaResponse) adapter.getItem(position - 1);
            ActivityUtils.intoQaDetailActivity(QaSearchActivity.this, resp);
        }
    };*/

    private void requstData(String content, String refresh) {
//        if (TextUtils.isEmpty(content)) {
//            return;
//        }
        manager.reqData(GlobalContext.getAccountId(), content, 1, 0, PAGE_COUNTS, adapter.getLastId(), refresh);
    }

    @Override
    public void onQaFailure(int errorCode, String errorMsg) {
        recyclerView.stopRefresh();
        adapter.changeMoreStatus(QAInfoAdapter.NO_LOAD_MORE);
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onQaSuccess(List<QaResponse> list) {
        // TODO Auto-generated method stub
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        recyclerView.stopRefresh();
        noDataLayout.setVisibility(View.GONE);
        backIV.setVisibility(View.VISIBLE);
        //收到数据
        if (null != list) {
            adapter.addBackwardList(list);
            if (0 == adapter.getList().size()) {
                noDataTV.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            } else {
                Utils.hideSoftInput(QaSearchActivity.this, clearEditText);
                noDataTV.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            }
        }
        adapter.changeMoreStatus(QAInfoAdapter.NO_LOAD_MORE);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void addOneData(QaResponse addData) {
        // TODO Auto-generated method stub

    }

    @Override
    public void removeOneData(int questId) {
        // TODO Auto-generated method stub
        adapter.removeOneData(questId);
    }

    @Override
    public void priseNotify(int questId, int isGood, int goodCounts) {
        // TODO Auto-generated method stub
        adapter.priseNotify(questId, isGood, goodCounts);
    }

    @Override
    public void replyNotify(int questId, int answerCounts) {
        // TODO Auto-generated method stub
        adapter.replyNotify(questId, answerCounts);
    }

    @Override
    public void visitorUpdate(int questId, int visitorCounts) {
        adapter.visitorUpdate(questId, visitorCounts);
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void itemClick(View v) {
        final int position;
        QaResponse resp;
        switch (v.getId()) {
            case R.id.qa_item_layout:
                position = (Integer) v.getTag(R.id.qa_item_layout);
                ActivityUtils.intoQaDetailActivity(QaSearchActivity.this, adapter.getList().get(position));
                break;
            case R.id.user_head:
                position = (Integer) v.getTag(R.id.user_head);
                resp = adapter.getList().get(position);
                ActivityUtils.intoHeadInfoActivity(resp.accountId, this);
                break;
            case R.id.user_name:
                position = (Integer) v.getTag(R.id.user_name);
                resp = adapter.getList().get(position);
                ActivityUtils.intoHeadInfoActivity(resp.accountId, this);
                break;
            case R.id.qa_content_tv:
                position = (Integer) v.getTag(R.id.qa_content_tv);
                resp = adapter.getList().get(position);
                ActivityUtils.intoQaDetailActivity(this, resp);
                break;
            case R.id.include_answer_tv:
                position = (Integer) v.getTag(R.id.include_answer_tv);
                resp = adapter.getList().get(position);
                ActivityUtils.intoQaDetailActivity(this, resp);
                break;
            case R.id.include_forward_tv:
                String imageUrl = null;
                position = (Integer) v.getTag(R.id.include_forward_tv);
                resp = adapter.getList().get(position);
                if (TextUtils.isEmpty(resp.questImgs)) {
                    imageUrl = GlobalContext.cdndownUrl + resp.userInfo.headPic;
                } else {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                    imageUrl = imageUrls.get(0);
                }
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(this, resp.content, 1, imageUrl, resp.id);
                break;
            case R.id.include_praise_tv:
                position = (Integer) v.getTag(R.id.include_praise_tv);
                resp = adapter.getList().get(position);
                if (resp.isGood == 0) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                QaDataChangeManager qaDataChangeManager = QaDataChangeManager.getInstance();
                qaDataChangeManager.priseNotify(adapter.getList().get(position).id, resp.isGood, resp.goodCount);
                goodclick(adapter.getList().get(position).id);
                break;
            case R.id.include_delete_tv:
                // 删除传入的参数是Id
                position = (Integer) v.getTag(R.id.include_delete_tv);
                CustomDialog.Builder builder = new CustomDialog.Builder(this);
                builder.setTitle("确认删除该条问答吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                QuestDelManager questDelManager = new QuestDelManager(QaSearchActivity.this);
                                questDelManager.deleteQuest(GlobalContext.getAccountId(), position);
                                QaDataChangeManager manager = QaDataChangeManager.getInstance();
                                manager.notifyRemove(position);
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            default:
                break;
        }
    }

    private void goodclick(int questId) {
        QuestGoodManager manager = new QuestGoodManager(this);
        manager.good(GlobalContext.getAccountId(), questId);
    }

}
